<template>
	<view class="layout">
		<view class="layout-nav">
			<DistributionNavBar title="素材上传" rgb="#fff">
				<template slot="left">
					<image :src="bankIcon" @click="clickBack" />
				</template>
			</DistributionNavBar>
		</view>

		<view class="layout-header">
			<view class="layout-header-hint" :class="{ 'show-warn': isShowWarn }">素材上传中，请勿退出程序</view>

			<view class="layout-header-content">
				<CommonMateriaHeader :isSkelett="isSkelett" :list="materialHintList" />
			</view>
		</view>

		<view class="layout-product">
			<DistributionMaterial :skelettSize="1" :isSkelett="isSkelett" :isFooter="false" :list="singleMaterialList" />
		</view>

		<view class="layout-main">
			<template v-if="isUploadStatusFileList">
				<CommonMateriaHint />
			</template>

			<template v-else>
				<MaterialResource
					:limit="hintParams"
					:isPreview="!isPreview"
					:list="uploadStatusFileList"
					@clickAgainUpload="clickAgainUpload"
					@delteUploadSuccessFile="deleteUploadSuccessFile"
				/>
			</template>
		</view>

		<CommonMateriaFooter>
			<template slot="footerButton">
				<view class="layout-footer">
					<button @click="openPhotoAlbum">一键上传</button>

					<button
						:loading="isLoading"
						@click="submitReview"
						:disabled="isSubmitReview || isLoading"
						:class="{
							active: isLoading,
							disabled: isSubmitReview
						}"
					>
						提交审核
					</button>
				</view>
			</template>
		</CommonMateriaFooter>
	</view>
</template>

<script>
import { defaultImageUrl } from '@/utils';
import EncapsulationUpload from '@/plugIn/upload';
import { formatCommissionsModel, hintUploadAndDownload } from '@/utils/common';
import { getResourceRule, uploadCallback, getSingleProductDetail } from '@/api/material';
import MaterialResource from './components/MaterialResource';
import CommonMateriaHint from './components/CommonMateriaHint';
import CommonMateriaFooter from './components/CommonMateriaFooter';
import CommonMateriaHeader from './components/CommonMateriaHeader';
import DistributionMaterial from '@/components/distributionMaterial';
import DistributionNavBar from '@/components/distributionNavBar/indeHome.vue';

const bankIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);

export default {
	name: 'MaterialUpload',

	data() {
		this.requestNumber = 0;

		return {
			bankIcon,
			hintParams: {},
			isSkelett: true,
			isLoading: false,

			singleMaterialList: [],
			uploadStatusFileList: [],
			materialHintList: [{}, {}]
		};
	},

	onLoad(params) {
		this.productId = Number(params?.productId || 0);

		this.getPageAllData();

		// #ifdef APP-PLUS
		this.getAppWebview = this.$mp.page.$getAppWebview();
		// #endif
	},

	computed: {
		isUploadStatusFileList() {
			const { uploadStatusFileList } = this;
			const isStatus = !uploadStatusFileList.length;

			// #ifdef APP-PLUS
			this.getAppWebview?.setStyle({
				popGesture: isStatus ? 'none' : 'close'
			});
			// #endif

			return isStatus;
		},

		isPreview() {
			const { uploadStatusFileList } = this;

			const status = uploadStatusFileList.some((item) => item.list.some((subItem) => subItem.status === 'upload'));

			return status;
		},

		isSubmitReview() {
			const {
				isPreview,
				isUploadStatusFileList,

				hintParams: { td_resource_rule_1, td_resource_rule_2 },
				statusTypeNumberObject: { imgNumber = 0, videoNumber = 0 }
			} = this;

			if (isUploadStatusFileList) {
				return true;
			}
			let minMediaNumber = Math.min(td_resource_rule_1, td_resource_rule_2);
			if (imgNumber + videoNumber < minMediaNumber) {
				return true;
			}
			// if (imgNumber < td_resource_rule_1 || videoNumber < td_resource_rule_2) {
			// 	return true;
			// }

			if (isPreview) {
				return true;
			}

			return false;
		},

		statusTypeNumberObject() {
			const { uploadStatusFileList } = this;
			const numberList = uploadStatusFileList.map((item) => {
				const { type, list } = item;

				const formatList = list.filter((subItem) => subItem.status === 'success');

				return [type === 'image' ? 'imgNumber' : 'videoNumber', formatList.length];
			});

			return Object.fromEntries(numberList);
		},

		isShowWarn() {
			const { uploadStatusFileList } = this;

			const status = uploadStatusFileList.some((item) => {
				return item.list.some((subItem) => subItem.status === 'upload');
			});

			return status;
		}
	},

	methods: {
		async clickBack() {
			const { isUploadStatusFileList } = this;

			if (isUploadStatusFileList) {
				uni.navigateBack();
				return;
			}

			const res = await hintUploadAndDownload();

			if (!res.confirm) {
				uni.navigateBack();
				this.upload.allAbortUpload();
				return;
			}
		},

		submitReview() {
			const { statusTypeNumberObject, singleMaterialList, uploadStatusFileList } = this;
			const [{ id, skuId = '', productTitle }] = singleMaterialList;
			const { imgNumber = 0, videoNumber = 0 } = statusTypeNumberObject;
			this.isLoading = true;

			const info = uploadStatusFileList
				.map((item) => {
					return item.list.map((subItem) => {
						const { name, otherParams } = subItem;

						return {
							name,
							...otherParams
						};
					});
				})
				.flat(2);
			const params = {
				imgNumber,
				videoNumber,
				info,
				skuId,
				seekNo: '', // 探店申请编号
				productId: id,
				uploadType: 1, // 上传类型：1产品上传；2探店上传；3原视频上传
				partnerName: productTitle
			};

			uploadCallback(params)
				.then((res) => {
					const { code, data } = res;

					if (code !== 200) {
						this.isLoading = false;
						return;
					}

					if (!data) {
						if (this.requestNumber >= 2) {
							this.isLoading = false;
							this.requestNumber = 0;

							uni.showToast({
								mask: true,
								icon: 'none',
								title: '网络繁忙，请稍候重试'
							});

							return;
						}

						++this.requestNumber;
						setTimeout((e) => {
							this.submitReview();
						}, 3000);
						return;
					}

					this.isLoading = false;

					uni.redirectTo({
						url: `/materialPage/MaterialReviewOrder?orderId=${id}&uploadNo=${data}&approveStatus=0`
					});
				})
				.catch((e) => {
					this.isLoading = false;
				});
		},

		getPageAllData() {
			const { productId } = this;
			Promise.all([getSingleProductDetail({ productId }), getResourceRule()]).then((res) => {
				const [productDetail, productRule] = res || [];

				const { commission, productName, productConfig, ...otherParams } = productDetail?.data || {};

				this.singleMaterialList = [
					{
						id: productId,
						...otherParams,
						productTitle: productName,
						commissionsList: formatCommissionsModel(commission)
					}
				];

				let hintParams = {};

				(productRule?.data || []).forEach((item) => {
					hintParams[item.code] = item.value;
				});

				this.hintParams = hintParams;
				const { imgSalePrice, imgCreatorPercent, videoSalePrice, videoCreatorPercent } = productConfig;

				const imageMoney = (imgSalePrice * imgCreatorPercent) / 1_0000;
				const videoMoney = (videoSalePrice * videoCreatorPercent) / 1_0000;
				let minMediaNumber = Math.min(hintParams.td_resource_rule_1, hintParams.td_resource_rule_2);

				const td_resource_rule_6 = hintParams.td_resource_rule_6 * 1
				const td_resource_rule_7 = hintParams.td_resource_rule_7 * 1

				this.materialHintList = [
					{
						label: `每次上传素材，图片+视频不少于${minMediaNumber}个，最多不超过${
							td_resource_rule_6 + td_resource_rule_7
						}个`
					},
					{
						label: `图片被下载预估收益${imageMoney.toFixed(2)}元/张，视频被下载预估收益${videoMoney.toFixed(2)}元/份`
					}
				];

				this.upload = new EncapsulationUpload({
					that: this,
					statusNumber: {
						maxImage: td_resource_rule_6,
						maxVideo: td_resource_rule_7
					}
				});

				this.$nextTick((e) => {
					this.isSkelett = false;
				});
			});
		},

		openPhotoAlbum() {
			const { isLoading } = this;

			if (isLoading) {
				return;
			}

			this.upload.openPhotoAlbum();
		},

		clickAgainUpload(params) {
			this.upload.singleAgainUpload(params);
		},

		deleteUploadSuccessFile(params) {
			this.upload.deleteSingleFile(params);
		}
	},

	// #ifdef APP-PLUS
	onBackPress(params) {
		const { from } = params;

		if (from === 'navigateBack') {
			return;
		}

		this.clickBack();
		return true;
	},
	// #endif

	onUnload() {
		const { statusTypeNumberObject } = this;

		Object.keys(statusTypeNumberObject).length && this.upload.allAbortUpload();
	},

	components: {
		DistributionNavBar,
		MaterialResource,
		CommonMateriaHint,
		CommonMateriaHeader,
		DistributionMaterial,
		CommonMateriaFooter
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	@include Db_iosBottomDistance(140rpx);

	&-nav {
		image {
			width: 40rpx;
			height: 40rpx;
			padding: 20rpx;
			margin-left: -20rpx;
		}
	}

	&-header {
		position: relative;

		&-hint {
			height: 0;
			position: sticky;
			overflow: hidden;
			background: #f55f4e;

			display: flex;
			align-items: center;
			justify-content: center;

			color: #fff;
			font-size: 24rpx;
			font-weight: 500;
			transition: height 0.3s;

			&.show-warn {
				height: 60rpx;
			}
		}

		&-content {
			padding: 20rpx 20rpx 0;
		}

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			height: 204rpx;
			background: linear-gradient(180deg, #fff7f2 0%, #f6f6f6 100%);
		}
	}

	&-product {
		margin-top: 20rpx;
		padding: 0 20rpx;
		position: relative;
	}

	&-main {
		padding: 0 20rpx;
		margin-top: 20rpx;
	}

	&-footer {
		display: flex;
		padding: 0 28rpx;

		button {
			flex: 1;
			@include Db_commonButton(80rpx, 24rpx);

			background: #ff6b11;

			&:active {
				background: rgba(255, 107, 17, 0.7);
			}

			&:first-child {
				margin-right: 10rpx;
				background: #fff;
				color: #ff6b11;
				border: 2rpx solid #ff6b11;
			}

			&:last-child {
				margin-left: 10rpx;
			}

			&.disabled {
				background: #ccc;
			}
		}
	}
}
</style>
